/**
 * \file generate.cpp
 * \author Ameen Jaber
 * \author Mohamad Noureddine
 * \author Mohamed Sabra
 * \brief Contains implementation of generation method
 * This program is responsible for generating a random graph matrix 
 * to be then translated into a pppgraph and a boost graph for testing
 */

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <ctime>
#include <string>

using namespace std;

int 
main(int argc, char *argv[]) {
    int vsize = 0; // size of vertices
    int opt;
    int ** matrix;
    int stop;
    int i, j; // index for matrix access
    string outfile = ""; // output file name 
    FILE * fp; // output file pointer

    while ((opt = getopt(argc, argv, "s:f:b")) != -1) { // loop over argv
        switch(opt) {
            case 's':
                vsize = atoi(optarg);
                break;
            case 'f':
                outfile += optarg;
                break;
            default:
                fprintf(stderr, "Usage: %s [-s {size of vertices}] [-f {output file}]\n", argv[0]);
                exit(EXIT_FAILURE);
        }
    }

    // error check
    if (vsize == 0 || outfile == "") {
        fprintf(stderr, "Usage: %s [-s {size of vertices}] [-f {output file}]\n", argv[0]);
        exit(EXIT_FAILURE);
    }
    
    std::cout << "Creating a graph with " << vsize << " vertices...\n";
    // allocate a random matrix of given input size 
    matrix = new int * [vsize];
    for (int r = 0 ; r < vsize ; r++) {
        matrix[r] = new int[vsize];
        for (int c = 0 ; c < vsize ; c++) 
            matrix[r][c] = 0;
    }
    
    stop = vsize*vsize/4;
    srand(time(NULL));
    for (int k = 0 ; k < stop ; k++) { //  loop vsize^2/4 times
        i = rand() % vsize;
        j = rand() % vsize;
        if (i != j) {
            matrix[i][j] = rand()%6; // assign a random weight from 0 to 5    
            matrix[j][i] = matrix[i][j]; // assign also the reciproqal since undirected graph
        }
    }

    std::cout << "Writing to file " << outfile << "...\n";
    // open output file 
    fp = fopen(outfile.c_str(), "w");// open file for reading 
    if (fp == NULL) {
        fprintf(stderr, "Cannot open output file %s\n",outfile.c_str() );
        exit(EXIT_FAILURE);
    }
    // print matrix to file 
    for (int r = 0 ; r < vsize ; r++) {
        for (int c = 0 ; c < vsize ; c++) {
            fprintf(fp, "%d " , matrix[r][c]);
        }
        fprintf(fp, "\n");
    }

    return EXIT_SUCCESS;
}
